package com.ihisun.tmhcms.core.service.projectservice.impl;

import com.ihisun.tmhcms.core.dto.projectdto.SearchProjectClassDto;
import com.ihisun.tmhcms.core.service.projectservice.ProjectClassService;
import com.ihisun.tmhcms.core.vo.SearchProjectClassVo;
import com.ihisun.tmhcms.utils.PageBean;
import com.ihisun.tmhcms.utils.ResponseVo;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigInteger;
import java.util.List;

@Service
public class ProjectClassServiceImpl implements ProjectClassService {
    @PersistenceContext
    EntityManager entityManager;

    @Override
    public ResponseVo searchProjectClass(SearchProjectClassDto searchProjectClassDto) {
        if (searchProjectClassDto.getState().equals(0)) {
            searchProjectClassDto.setState(1);
        }

        StringBuilder sql = new StringBuilder("select * from p_project_class where state!=3");

        if (searchProjectClassDto.getClassName() != null && !"".equals(searchProjectClassDto.getClassName())) {
            sql.append(" and project_class_name=" + searchProjectClassDto.getClassName() + "");
        }
        if (searchProjectClassDto.getState() != null) {
            sql.append(" and state=" + searchProjectClassDto.getState() + "");
        }
        sql.append(" limit " + (searchProjectClassDto.getPageNum() - 1) * 10 + "," + searchProjectClassDto.getPageSize() + "");

        List<SearchProjectClassVo> resultList = entityManager.createNativeQuery(sql.toString(), SearchProjectClassVo.class).getResultList();

        StringBuilder countSql = new StringBuilder("select count(*) from p_project_class where state!=3");

        if (searchProjectClassDto.getClassName() != null && !"".equals(searchProjectClassDto.getClassName())) {
            countSql.append(" and project_class_name=" + searchProjectClassDto.getClassName() + "");
        }
        if (searchProjectClassDto.getState() != null) {
            countSql.append(" and state=" + searchProjectClassDto.getState() + "");
        }
        BigInteger singleResult = (BigInteger) entityManager.createNativeQuery(countSql.toString()).getSingleResult();
        PageBean pageBean = new PageBean(searchProjectClassDto.getPageNum(), singleResult.intValue(), searchProjectClassDto.getPageSize(), resultList);
        return ResponseVo.ok(pageBean);
    }
}
